/*
 * @FilePath: /three/src/utils/defaHttp/index.ts
 * 介绍:axios工具封装
 */
import axios, { AxiosRequestConfig } from "axios";

const env = import.meta.env;

if (env.VITE_PROXY == "1") {
  axios.defaults.baseURL = env.VITE_API_PREFIX; //配置默认请求地址--跨域代理
} else {
  axios.defaults.baseURL = env.VITE_BASE_URL + env.VITE_API_PREFIX; //配置默认请求地址--无代理
}
// axios.defaults.headers.post["Content-Type"] =
//   "application/x-www-form-urlencoded";
/**
 * * 请求拦截器
 */
axios.interceptors.request.use((config: AxiosRequestConfig) => {
  //配置token
  const headers: { [key: string]: any } = { ...config.headers };
  if (true) {
    headers.token = "token";
  }
  return { ...config, headers }; //请求配置项
});
/**
 * * 响应拦截器
 */
axios.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    //对错误进行统一处理
    console.error("请求错误--", error);
    return Promise.resolve(error);
  }
);

export default {
  async get<T>(url: string, config?: object, mode: Mode[] = []): Promise<T> {
    await before(mode);
    const res = await axios.get(url, config);
    return await after(mode, res);
  },
  async post<T>(url: string, config?: object, mode: Mode[] = []): Promise<T> {
    await before(mode);
    const res = await axios.post(url, config);
    return await after(mode, res);
  },
  async put<T>(url: string, config?: object, mode: Mode[] = []): Promise<T> {
    await before(mode);
    const res = await axios.put(url, config);
    return await after(mode, res);
  },
  async delete<T>(url: string, config?: object, mode: Mode[] = []): Promise<T> {
    await before(mode);
    const res = await axios.delete(url, config);
    return await after(mode, res);
  },
};
type Mode = "show" | "showError" | "showSucceed" | "showLoading";
/**请求前 */
async function before(mode: Mode[]) {
  if (mode.includes("showLoading")) {
    // Message.loading();
  }
}
/**请求后 */
async function after(mode: Mode[], res: any): Promise<any> {
  if (mode.includes("showLoading")) {
    // Message.close();
  }
  if (res.code != 200) {
    if (mode.includes("show") || mode.includes("showError")) {
      // Message.error(res.msg || "服务器错误 !");
    }
  } else {
    if (mode.includes("showSucceed") || mode.includes("show")) {
      // Message.succeed(res.msg || "成功 !");
    }
  }
  return res;
}
